package com.du.dupload;

import java.awt.Component;
import java.awt.Container;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TasksManager {
	private static TasksManager instance;
	private List<Pair<ManagerCallback, IUICallback>> managers = new ArrayList<Pair<ManagerCallback, IUICallback>>();
	private Container container;
	private List<IResourceDownloader> downloads;
	private List<List<String>> uploads;
	private List<List<String>> converts;

	private TasksManager() {
		downloads = new ArrayList<IResourceDownloader>();
		uploads = new ArrayList<List<String>>();
		converts = new ArrayList<List<String>>();
	}

	public static void initializePanel(Container cont) {
		getInstance().container = cont;
	}

	public static TasksManager getInstance() {
		if (instance == null) {
			instance = new TasksManager();
		}
		return instance;
	}

	public void addTask(IResourceDownloader rd) {
		if (downloads.contains(rd)) {
			return;
		}
		SwingItemProgress swingItem = new SwingItemProgress();
		IUICallback ui = (IUICallback) Proxy.newProxyInstance(getClass()
				.getClassLoader(), new Class[] { IUICallback.class },
				new EDTInvocationHandler(swingItem));
		ManagerCallback mc = new ProcessManager(ui, rd, this);
		Pair<ManagerCallback, IUICallback> item = new Pair<ManagerCallback, IUICallback>(
				mc, ui);
		managers.add(item);
		container.add(swingItem);
		downloads.add(rd);
		swingItem.setAlignmentX(Component.LEFT_ALIGNMENT);
		mc.currentTaskIsFinished("Starting");
	}

	public void addTaskConvert(List<String> list) {
		if (converts.contains(list)) {
			return;
		}
		SwingItemProgress swingItem = new SwingItemProgress();
		IUICallback ui = (IUICallback) Proxy.newProxyInstance(getClass()
				.getClassLoader(), new Class[] { IUICallback.class },
				new EDTInvocationHandler(swingItem));
		ManagerCallback mc = new ProcessManager(ui, list, this);
		Pair<ManagerCallback, IUICallback> item = new Pair<ManagerCallback, IUICallback>(
				mc, ui);
		managers.add(item);
		container.add(swingItem);
		converts.add(list);
		swingItem.setAlignmentX(Component.LEFT_ALIGNMENT);
		mc.currentTaskIsFinished("Downloading");
	}

	public void addTaskUpload(List<String> list) {
		if (uploads.contains(list)) {
			return;
		}
		SwingItemProgress swingItem = new SwingItemProgress();
		IUICallback ui = (IUICallback) Proxy.newProxyInstance(getClass()
				.getClassLoader(), new Class[] { IUICallback.class },
				new EDTInvocationHandler(swingItem));
		ManagerCallback mc = new ProcessManager(ui, list, this, true);
		Pair<ManagerCallback, IUICallback> item = new Pair<ManagerCallback, IUICallback>(
				mc, ui);
		managers.add(item);
		container.add(swingItem);
		uploads.add(list);
		swingItem.setAlignmentX(Component.LEFT_ALIGNMENT);
		mc.currentTaskIsFinished("Converting");
	}



}
